package me.hekr.demo;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.litesuits.common.assist.Toastor;

import me.hekr.hekrsdk.HekrOAuthLoginActivity;
import me.hekr.hekrsdk.action.HekrUser;
import me.hekr.hekrsdk.action.HekrUserAction;
import me.hekr.hekrsdk.bean.JWTBean;
import me.hekr.hekrsdk.bean.MOAuthBean;
import me.hekr.hekrsdk.util.HekrCodeUtil;
import me.hekr.hekrsdk.util.HekrCommonUtil;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_username, et_pwd;
    private HekrUserAction hekrUserAction;
    private Toastor toastor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        hekrUserAction = HekrUserAction.getInstance(this);
        if (TextUtils.isEmpty(hekrUserAction.getJWT_TOKEN())) {
            setTitle("登录");
            initView();
            initData();
        } else {
            startActivity(new Intent(this, DeviceListActivity.class));
            finish();
        }
    }

    private void initData() {
        toastor = new Toastor(this);
        hekrUserAction = HekrUserAction.getInstance(this);
    }

    private void initView() {
        et_username = (EditText) findViewById(R.id.et_username);
        et_pwd = (EditText) findViewById(R.id.et_pwd);
        Button btn_login = (Button) findViewById(R.id.btn_login);
        Button btn_qq = (Button) findViewById(R.id.btn_qq);
        Button btn_wechat = (Button) findViewById(R.id.btn_wechat);
        Button btn_weibo = (Button) findViewById(R.id.btn_weibo);


        if (btn_login != null) {
            btn_login.setOnClickListener(this);
        }
        if (btn_wechat != null) {
            btn_wechat.setOnClickListener(this);
        }
        if (btn_weibo != null) {
            btn_weibo.setOnClickListener(this);
        }
        if (btn_qq != null) {
            btn_qq.setOnClickListener(this);
        }


    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_login, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.action_phone:
                startActivity(new Intent(LoginActivity.this, RegisterByPhoneActivity.class));
                return true;
            case R.id.action_email:
                registerEmailDialog();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                String username = et_username.getText().toString().trim();
                String pwd = et_pwd.getText().toString().trim();
                if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(pwd)) {
                    hekrUserAction.login(username, pwd, new HekrUser.LoginListener() {
                        @Override
                        public void loginSuccess(String str) {
                            startActivity(new Intent(LoginActivity.this, DeviceListActivity.class));
                            finish();
                        }

                        @Override
                        public void loginFail(int errorCode) {
                            toastor.showSingleLongToast(HekrCodeUtil.errorCode2Msg(errorCode));
                        }
                    });
                } else {
                    toastor.showSingleLongToast("请输入完整！");
                }
                break;
            case R.id.btn_qq:
                Intent intent = new Intent(LoginActivity.this, HekrOAuthLoginActivity.class);
                intent.putExtra(HekrOAuthLoginActivity.OAUTH_TYPE, HekrUserAction.OAUTH_QQ);
                startActivityForResult(intent, HekrUserAction.OAUTH_QQ);
                break;
            case R.id.btn_wechat:
                Intent intent2 = new Intent(LoginActivity.this, HekrOAuthLoginActivity.class);
                intent2.putExtra(HekrOAuthLoginActivity.OAUTH_TYPE, HekrUserAction.OAUTH_WECHAT);
                startActivityForResult(intent2, HekrUserAction.OAUTH_WECHAT);
                break;
            case R.id.btn_weibo:
                Intent intent3 = new Intent(LoginActivity.this, HekrOAuthLoginActivity.class);
                intent3.putExtra(HekrOAuthLoginActivity.OAUTH_TYPE, HekrUserAction.OAUTH_SINA);
                startActivityForResult(intent3, HekrUserAction.OAUTH_SINA);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            String certificate = data.getStringExtra(HekrOAuthLoginActivity.OAUTH_CODE);
            if (!TextUtils.isEmpty(certificate)) {
                loginOAuth(resultCode, certificate);
            }
        }
    }

    //移动端OAuth接口
    private void loginOAuth(final int type, String certificate) {
        //通过上一步拿到的certificate进行第三方登录
        hekrUserAction.OAuthLogin(type, certificate, new HekrUser.MOAuthListener() {
            @Override
            public void mOAuthSuccess(MOAuthBean moAuthBean) {
                //该OAuth账号还未和主账号绑定
                createUserAndBind(type, moAuthBean.getBindToken());
            }

            @Override
            public void mOAuthSuccess(JWTBean jwtBean) {
                //该OAuth账号已经和主账号绑定
                startActivity(new Intent(LoginActivity.this, DeviceListActivity.class));
                finish();
            }

            @Override
            public void mOAuthFail(int errorCode) {
                //失败
                toastor.showSingleLongToast(HekrCodeUtil.errorCode2Msg(errorCode));
            }
        });
    }


    //创建匿名帐号并且绑定
    private void createUserAndBind(final int type, final String bindToken) {
        hekrUserAction.createUserAndBind(type, bindToken, new HekrUser.CreateUserAndBindListener() {
            @Override
            public void createSuccess(String str) {
                startActivity(new Intent(LoginActivity.this, DeviceListActivity.class));
                finish();
            }

            @Override
            public void createFail(int errorCode) {
                toastor.showSingleLongToast(HekrCodeUtil.errorCode2Msg(errorCode));
            }
        });
    }


    /**
     * 邮箱注册
     */
    private void registerEmailDialog() {
        View view = View.inflate(this, R.layout.layout_register_email, null);
        final TextInputEditText et_email = (TextInputEditText) view.findViewById(R.id.et_email);
        final TextInputEditText et_pwd = (TextInputEditText) view.findViewById(R.id.et_pwd);
        final AlertDialog alertDialog = new AlertDialog.Builder(this).setView(view).setTitle("邮箱注册")
                .setPositiveButton("发送邮件", null).setNegativeButton("取消", null)
                .setCancelable(false).create();
        alertDialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                alertDialog.getButton(Dialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        final String email = et_email.getText().toString().trim();
                        String pwd = et_pwd.getText().toString().trim();
                        //此处注意校验用户输入是否为正确邮箱格式
                        hekrUserAction.registerByEmail(email, pwd, new HekrUser.RegisterListener() {
                            @Override
                            public void registerSuccess(String uid) {
                                toastor.showSingletonToast(uid + "\n发送邮件成功,请进入邮箱激活,激活后即可直接登录");
                            }

                            @Override
                            public void registerFail(int errorCode) {
                                toastor.showSingletonToast(HekrCodeUtil.errorCode2Msg(errorCode));
                            }
                        });
                    }
                });
            }
        });
        alertDialog.show();
    }


    /**
     * 重新发送激活邮件
     *
     * @param email 邮箱地址
     */
    private void reSendVerifiedEmail(String email) {
        hekrUserAction.reSendVerifiedEmail(email, new HekrUser.ReSendVerifiedEmailListener() {
            @Override
            public void reSendVerifiedEmailSuccess() {
                toastor.showSingletonToast("\n重新发送邮件成功,请进入邮箱激活,激活后即可直接登录");
            }

            @Override
            public void reSendVerifiedEmailFail(int errorCode) {
                toastor.showSingletonToast(HekrCodeUtil.errorCode2Msg(errorCode));
            }
        });
    }


}
